#!/bin/bash

# Simplified sanity check script without database verification
# Focuses on client-side metrics and server logs

set -e

echo "==============================================="
echo "     Performance Sanity Check (Simplified)"
echo "==============================================="

# Configuration parameters - MUST be identical for both tests
TOTAL_RECORDS=100000  # Reduced for faster testing
BATCH_SIZE=1000
LINGER_MS=10
CONCURRENCY=4
MODE="stream"

# Build the benchmark
echo -e "\n[1/5] Building benchmark..."
cd /home/xiaodouzi/workspace/422a67685e23f903e048434351289787/build
make bench_write_new -j4 > /dev/null 2>&1

# Test 1: UDS Mode
echo -e "\n[2/5] Running UDS benchmark..."
echo "Config: records=$TOTAL_RECORDS batch=$BATCH_SIZE linger=$LINGER_MS threads=$CONCURRENCY"

# Clear server log
> /tmp/ingestd.log

UDS_OUTPUT=$(./bench/cpp/bench_write_new \
    --mode $MODE \
    --transport uds \
    --path /tmp/kwdb.sock \
    --records $TOTAL_RECORDS \
    --batch-size $BATCH_SIZE \
    --linger-ms $LINGER_MS \
    --concurrency $CONCURRENCY \
    2>&1)

echo "$UDS_OUTPUT" > /tmp/uds_test.log

# Extract UDS metrics
UDS_QPS=$(echo "$UDS_OUTPUT" | grep "^QPS:" | awk '{print $2}')
UDS_SUCCESS=$(echo "$UDS_OUTPUT" | grep "^Writes OK:" | awk '{print $3}')
UDS_TIME=$(echo "$UDS_OUTPUT" | grep "^Total Time:" | awk '{print $3}')
echo "UDS Results: QPS=$UDS_QPS, Success=$UDS_SUCCESS, Time=${UDS_TIME}ms"

# Check server log for UDS
echo "Server monitoring (last 5 lines):"
tail -5 /tmp/ingestd.log | grep MONITOR || echo "No monitoring data"

# Wait a bit
echo -e "\n[3/5] Waiting 2 seconds before TCP test..."
sleep 2

# Test 2: TCP Mode
echo -e "\n[4/5] Running TCP benchmark..."
echo "Config: records=$TOTAL_RECORDS batch=$BATCH_SIZE linger=$LINGER_MS threads=$CONCURRENCY"

# Clear server log
> /tmp/ingestd.log

TCP_OUTPUT=$(./bench/cpp/bench_write_new \
    --mode $MODE \
    --transport tcp \
    --host 127.0.0.1 \
    --port 9009 \
    --records $TOTAL_RECORDS \
    --batch-size $BATCH_SIZE \
    --linger-ms $LINGER_MS \
    --concurrency $CONCURRENCY \
    2>&1)

echo "$TCP_OUTPUT" > /tmp/tcp_test.log

# Extract TCP metrics
TCP_QPS=$(echo "$TCP_OUTPUT" | grep "^QPS:" | awk '{print $2}')
TCP_SUCCESS=$(echo "$TCP_OUTPUT" | grep "^Writes OK:" | awk '{print $3}')
TCP_TIME=$(echo "$TCP_OUTPUT" | grep "^Total Time:" | awk '{print $3}')
echo "TCP Results: QPS=$TCP_QPS, Success=$TCP_SUCCESS, Time=${TCP_TIME}ms"

# Check server log for TCP
echo "Server monitoring (last 5 lines):"
tail -5 /tmp/ingestd.log | grep MONITOR || echo "No monitoring data"

# Analysis
echo -e "\n[5/5] Analysis Results:"
echo "==============================================="
echo "Configuration Used:"
echo "  - Mode: $MODE"
echo "  - Total Records: $TOTAL_RECORDS"
echo "  - Batch Size: $BATCH_SIZE"
echo "  - Linger MS: $LINGER_MS"
echo "  - Concurrency: $CONCURRENCY"
echo ""
echo "UDS Performance:"
echo "  - QPS: $UDS_QPS"
echo "  - Time: ${UDS_TIME}ms"
echo "  - Success Count: $UDS_SUCCESS"
echo "  - Success Rate: $([ "$UDS_SUCCESS" = "$TOTAL_RECORDS" ] && echo "100%" || echo "$((UDS_SUCCESS * 100 / TOTAL_RECORDS))%")"
echo ""
echo "TCP Performance:"
echo "  - QPS: $TCP_QPS"
echo "  - Time: ${TCP_TIME}ms"
echo "  - Success Count: $TCP_SUCCESS"
echo "  - Success Rate: $([ "$TCP_SUCCESS" = "$TOTAL_RECORDS" ] && echo "100%" || echo "$((TCP_SUCCESS * 100 / TOTAL_RECORDS))%")"
echo ""

# Calculate ratio
if [ -n "$TCP_QPS" ] && [ -n "$UDS_QPS" ] && [ "$TCP_QPS" != "0" ]; then
    # Use awk for floating point division
    RATIO=$(echo "$UDS_QPS $TCP_QPS" | awk '{printf "%.2f", $1/$2}')
    echo "Performance Ratio (UDS/TCP): ${RATIO}x"

    # Check if ratio is reasonable
    if (( $(echo "$RATIO > 10" | bc -l) )); then
        echo ""
        echo "⚠️  WARNING: Ratio seems unusually high (${RATIO}x)"
        echo "    Normal UDS advantage is typically 1.2x-3x"
        echo "    Please check:"
        echo "    - Both tests used same configuration"
        echo "    - Client metrics count individual points, not batches"
        echo "    - Server is processing all requests correctly"
    fi
else
    echo "Performance Ratio: Unable to calculate"
fi

echo ""
echo "Data Integrity Check:"
if [ "$UDS_SUCCESS" = "$TOTAL_RECORDS" ]; then
    echo "  UDS: ✓ All points sent successfully"
else
    echo "  UDS: ✗ Only $UDS_SUCCESS/$TOTAL_RECORDS points sent"
fi

if [ "$TCP_SUCCESS" = "$TOTAL_RECORDS" ]; then
    echo "  TCP: ✓ All points sent successfully"
else
    echo "  TCP: ✗ Only $TCP_SUCCESS/$TOTAL_RECORDS points sent"
fi

echo ""
echo "Detailed logs saved to:"
echo "  - UDS: /tmp/uds_test.log"
echo "  - TCP: /tmp/tcp_test.log"
echo "  - Server: /tmp/ingestd.log"

echo "==============================================="